package yxy.game.pm2.command.friend;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.friend.FriendModule;
import yxy.game.pm2.module.friend.NeedFriendList;

/** 好友 删除好友 */
@MessageType(proto = Command.FriendDelete, classtype = FriendMessage.FriendDeleteRequest.class)
public class CMD_FriendDelete extends Command<FriendMessage.FriendDeleteRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendDeleteRequest request) {
		String playerCode = messageSource.getTag();
		String deleteCode = request.getPlayerCode();

		FriendMessage.FriendDeleteResponse.Builder response = FriendMessage.FriendDeleteResponse.newBuilder();

		FriendModule friendModule = FriendModule.get(playerCode);
		FriendModule deleteModule = FriendModule.get(deleteCode);
		try {
			if (friendModule.tryLock() && deleteModule.tryLock()) {
				// 各种关系表中删除
				friendModule.getFriend().remove(deleteCode);
				friendModule.getApply().remove(deleteCode);

				deleteModule.getFriend().remove(playerCode);
				deleteModule.getApply().remove(playerCode);

				PlayerBean playerBean = PlayerBean.get(playerCode);
				ServerBean serverBean = ServerBean.get(playerBean.getServerId());
				AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

				// 更新求好友列表
				NeedFriendList needFriendList = new NeedFriendList(areaBean.getGroupId());
				needFriendList.update(friendModule);
				needFriendList.update(deleteModule);

				friendModule.set();
				deleteModule.set();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			friendModule.unlock();
			deleteModule.unlock();
		}
	}

	private void send(MessageSource messageSource, FriendMessage.FriendDeleteResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}